<!--
 * @Description: 
 * @Version: V1.0.0
 * @Author: 周艳凯 484894717@qq.com
 * @Date: 2024-09-27 16:48:55
 * @LastEditors: 周艳凯 484894717@qq.com
 * @LastEditTime: 2024-10-22 14:30:15
 * @FilePath: index.vue
 * Copyright 2024 Marvin, All Rights Reserved. 
 * 2024-09-27 16:48:55
-->
<template>
  <!-- <div :class="classNames"> -->
  <a-row v-bind="rowProp" :class="classNames">
    <a-col :span="5" v-bind="da" :class="labelColCls">
      <!-- <div class="form-item-label">
        <slot name="label">{{ label }}</slot>
      </div> -->
      <labels v-bind="labelProps">
        {{ label }}
      </labels>
    </a-col>
    <a-col v-bind="mergedWrapperCol" :span="19" :class="wrapperColCls">
      <div class="arco-form-item-content-wrapper">
        <div :class="contentStyle">
          <slot></slot>
        </div>
      </div>
      <div v-if="$slots.extra" class="arco-form-item-extra">
        <slot name="extra">{{ extra }}</slot>
      </div>
      <div
        v-if="$slots.help || help"
        class="arco-form-item-message arco-form-item-message-help"
      >
        <slot name="help">{{ help }}</slot>
      </div>
      <mess :error="finalMessage"> </mess>
      <!-- <div v-if="$slots.help" class="arco-form-item-help">
        <slot name="help"></slot>
        <mess></mess>
      </div> -->
    </a-col>
  </a-row>
  <!-- </div> -->
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  inject,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import aRow from "../arco-row/index.vue";
import aCol from "../arco-col/index.vue";
import context from "../arco-form/context";
import labels from "./label.vue";
import mess from "./item-message.vue";
import { Schema } from "b-validate";
import { getValueByPath, setValueByPath } from "./gets";
import { getFinalValidateMessage } from "./utlis";
// import svgIcon from "../arco-icon/index.vue";
// var __hasOwnProp = Object.prototype.hasOwnProperty;
// var __getOwnPropSymbols = Object.getOwnPropertySymbols;
// var __propIsEnum = Object.prototype.propertyIsEnumerable;
// var __objRest = (source, exclude) => {
//   var target = {};
//   for (var prop in source)
//     if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
//       target[prop] = source[prop];
//   if (source != null && __getOwnPropSymbols)
//     // eslint-disable-next-line no-redeclare
//     for (var prop of __getOwnPropSymbols(source)) {
//       console.log("我是哦什么sim");
//       if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
//         target[prop] = source[prop];
//     }
//   // console.log(source, exclude, "我是几个值？");
//   return target;
// };

const icon = defineComponent({
  name: "Card",
  options: {
    // 虚拟化节点
    virtualHost: true,
  },
  components: {
    aRow,
    aCol,
    labels,
    mess,
    // svgIcon,
  },
  props: {
    field: {
      type: String,
      default: "",
    },
    rowProps: Object,
    label: String,
    tooltip: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: void 0,
    },
    contentFlex: {
      type: Boolean,
      default: true,
    },
    contentClass: [String, Array, Object],
    help: String,
    extra: String,
    required: {
      type: Boolean,
      default: false,
    },
    labelColProps: Object,
    wrapperColProps: Object,
    labelColFlex: {
      type: [Number, String],
    },
    hideAsterisk: {
      type: Boolean,
      default: false,
    },
    showColon: {
      type: Boolean,
      default: false,
    },
    asteriskPosition: {
      type: String,
      default: "start",
    },
    validateStatus: {
      type: String,
    },
    rules: {
      type: [Object, Array],
    },
    noStyle: {
      type: Boolean,
      default: false,
    },
  },
  emits: {
    close: () => true,
    afterClose: () => true,
  },
  setup(props) {
    const prefixCls = "arco-form-item";
    const { field } = toRefs(props);
    const formCtx = inject(context.formInjectionKey, {});

    const mergedLabelCol = computed(() => {
      var _a;
      const colProps =
        (_a = props.labelColProps) != null ? _a : formCtx.labelColProps;
      if (props.labelColFlex) {
        colProps.flex = props.labelColFlex;
      } else if (formCtx.autoLabelWidth) {
        let maxLabelWidth = 0;
        const values = Object.values(formCtx.labelWidth) as number[];
        if (values.length === 0) {
          maxLabelWidth = 0;
        } else {
          maxLabelWidth = values.reduce(
            (max, value) => Math.max(max, value),
            -Infinity,
          );
          console.log(maxLabelWidth, "我很无语是不是这样");
        }

        colProps.flex = `${maxLabelWidth}px`;
      }
      return colProps;
    });

    const da = reactive({
      flex: "auto",
    });

    watch(formCtx.labelWidth, (val) => {
      console.log(val, "我发生变化了");
      const values = Object.values(formCtx.labelWidth) as number[];
      const s1321 = values.reduce(
        (max, value) => Math.max(max, value),
        -Infinity,
      );
      console.log(s1321, "好无语的玩意");
      da.flex = `${s1321}px`;
    });

    const mergedWrapperCol = computed(() => {
      var _a;
      const colProps =
        (_a = props.wrapperColProps) != null ? _a : formCtx.wrapperColProps;

      if (props.labelColFlex || formCtx.autoLabelWidth) {
        colProps.flex = "auto";
      }

      return colProps;
    });

    const rowProp = computed(() => {
      var _a;
      const riwPropObject = (_a = props.rowProps) != null ? _a : {};
      riwPropObject.wrap = !(props.labelColFlex || formCtx.autoLabelWidth);
      return riwPropObject;
    });

    const computedDisabled = computed(() => {
      var _a;
      return Boolean(
        (_a = props.disabled) != null
          ? _a
          : formCtx == null
            ? void 0
            : formCtx.disabled,
      );
    });

    // const finalStatus = computed(() =>
    //   utils.getFinalValidateStatus(validateStatus),
    // );

    // const computedValidateStatus = computed(() => {
    //   var _a;
    //   return (_a = props.validateStatus) != null ? _a : finalStatus.value;
    // });
    // const isError = computed(() => computedValidateStatus.value === "error");
    const initialValue = getValueByPath(formCtx.model, props.field);
    const validateDisabled = ref(false);
    const validateStatus = reactive({});
    const validateMessage = reactive({});
    const fieldValue = computed(() =>
      getValueByPath(formCtx.model, props.field),
    );

    // 报错的信息
    const finalMessage = computed(() =>
      getFinalValidateMessage(validateMessage),
    );

    console.log(finalMessage, "我想不到");

    const formItemCtx = props.noStyle
      ? inject(context.formItemInjectionKey, void 0)
      : void 0;
    const updateValidateState = (field2, { status, message }) => {
      validateStatus[field2] = status;
      validateMessage[field2] = message;
      if (props.noStyle) {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        formItemCtx == null
          ? void 0
          : formItemCtx.updateValidateState(field2, { status, message });
      }
    };

    onMounted(() => {
      var _a;
      if (formItemInfo.field) {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        (_a = formCtx.addField) == null
          ? void 0
          : _a.call(formCtx, formItemInfo);
      }
    });

    const mergedRules = computed(() => {
      var _a, _b, _c;
      const baseRules = [].concat(
        (_c =
          (_b = props.rules) != null
            ? _b
            : (_a = formCtx == null ? void 0 : formCtx.rules) == null
              ? void 0
              : _a[props.field]) != null
          ? _c
          : [],
      );
      const hasRequiredRule = baseRules.some((item) => item.required);
      if (props.required && !hasRequiredRule) {
        return [{ required: true }].concat(baseRules);
      }
      return baseRules;
    });

    const validateField = () => {
      // var _b;
      if (validateDisabled.value) {
        return Promise.resolve();
      }
      const rules = mergedRules.value;
      // console.log(mergedRules, "我真的嘿嘿");
      if (!field.value || rules.length === 0) {
        // if (finalStatus.value) {
        //   clearValidate();
        // }
        return Promise.resolve();
      }
      const _field = field.value;
      const _value = fieldValue.value;
      updateValidateState(_field, {
        status: "",
        message: "",
      });
      const schema = new Schema(
        {
          [_field]: rules.map((_a) => {
            // var rule = __objRest(_a, []);
            let rule = _a;
            if (!rule.type && !rule.validator) {
              rule.type = "string";
            }
            return rule;
          }),
        },
        {
          ignoreEmptyString: true,
          // validateMessages:
          //   (_b = i18nMessage.value.form) == null
          //     ? void 0
          //     : _b.validateMessages,
          // validateMessages: void 0,
        },
      );
      return new Promise((resolve) => {
        schema.validate({ [_field]: _value }, (err) => {
          var _a;
          const isError2 = Boolean(err == null ? void 0 : err[_field]);
          updateValidateState(_field, {
            status: isError2 ? "error" : "",
            message:
              (_a = err == null ? void 0 : err[_field].message) != null
                ? _a
                : "",
          });
          const error = isError2
            ? {
                label: props.label,
                field: field.value,
                value: err[_field].value,
                type: err[_field].type,
                isRequiredError: Boolean(err[_field].requiredError),
                message: err[_field].message,
              }
            : void 0;
          resolve(error);
        });
      });
    };

    // 清除
    const clearValidate = () => {
      if (field.value) {
        updateValidateState(field.value, {
          status: "",
          message: "",
        });
      }
    };

    // 重置
    const resetField = () => {
      console.log(initialValue, "我已经想笑了");
      clearValidate();
      validateDisabled.value = true;
      if ((formCtx == null ? void 0 : formCtx.model) && field.value) {
        setValueByPath(formCtx.model, field.value, initialValue);
      }
      nextTick(() => {
        validateDisabled.value = false;
      });
    };

    const formItemInfo = reactive({
      field,
      disabled: computedDisabled,
      // error: isError,
      validate: validateField,
      clearValidate,
      resetField,
      // setField,
    });

    const classNames = computed(() => {
      return [
        prefixCls,
        // `${prefixCls}-${props.type}`,
        // {
        //   [`${prefixCls}-with-title`]: Boolean(props.title || slots.title),
        //   [`${prefixCls}-banner`]: props.banner,
        //   [`${prefixCls}-center`]: props.center,
        // },
      ];
    });

    const contentStyle = computed(() => {
      return [
        `${prefixCls}-content`,
        {
          [`${prefixCls}-content-flex`]: props.contentFlex,
        },
        props.contentClass,
      ];
    });

    const labelColCls = computed(() => [
      `${prefixCls}-label-col`,
      {
        [`${prefixCls}-label-col-left`]: formCtx.labelAlign === "left",
        [`${prefixCls}-label-col-flex`]:
          formCtx.autoLabelWidth || props.labelColFlex,
      },
    ]);

    const wrapperColCls = computed(() => [
      `${prefixCls}-wrapper-col`,
      {
        [`${prefixCls}-wrapper-col-flex`]: !mergedWrapperCol.value,
      },
    ]);

    const labelProps = {
      // required: props.hideAsterisk ? false : props.isRequired,
      required: true,
      "show-colon": props.showColon,
      "asterisk-position": props.asteriskPosition,
      tooltip: props.tooltip,
    };

    return {
      prefixCls,
      classNames,
      contentStyle,
      labelColCls,
      wrapperColCls,
      labelProps,
      finalMessage,
      mergedLabelCol,
      mergedWrapperCol,
      da,
      rowProp,
    };
  },
});
export default icon;
</script>

<style lang="scss">
// @import "./index.scss";
</style>
